package spring.cloud.tasks.client.item_task_processor.pooled.timer_task;

import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import spring.cloud.tasks.client.item_task_processor.ProcessorStatusEnum;
import spring.cloud.tasks.client.item_task_processor.TaskProcessor;
import spring.cloud.tasks.client.item_task_processor.pooled.impl.TaskHeartBeatPooledImpl;

import java.util.Date;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;


@Slf4j
@Getter
@Setter
public class TaskHeartBeatTask implements Runnable {
    private String heartBeatRateString;

    public TaskHeartBeatTask(String heartBeatRateString) {
        this.heartBeatRateString = heartBeatRateString;
    }

    @Override
    public void run() {
        String initState = "";
        Map<String, TaskProcessor> taskMap = TaskHeartBeatPooledImpl.heartBeatRateStringToTaskProcessorIdToTaskProcessorMapMap.row(heartBeatRateString);
        if (taskMap != null) {
            Set<Map.Entry<String, TaskProcessor>> entrySet = new HashSet<Map.Entry<String, TaskProcessor>>(taskMap.entrySet());
            for (Map.Entry<String, TaskProcessor> entry : entrySet) {
                TaskProcessor taskProcessor = entry.getValue();
                if (ProcessorStatusEnum.dead.toString().equals(taskProcessor.getTaskProcessorInfo().getState())) {
                    continue;
                }
                try {
                    taskProcessor.pongpong();
                    taskProcessor.getTaskProcessorInfo().setHeartBeatTime(new Date());
                    if (initState.equals(entry.getValue().getTaskProcessorInfo().getState())) {
                        entry.getValue().getTaskProcessorInfo().setState(ProcessorStatusEnum.normal.toString());
                    }
                } catch (Exception e) {

                }

            }
        }
    }
}
